import collections


class Solution(object):
    def lengthOfLongestSubstringTwoDistinct(self, s):
        """
        :type s: str
        :rtype: int
        """
        n = len(s)
        l_index = 0
        r_index = 0
        max_length = -1
        table = collections.defaultdict(int)
        while r_index < n:
            table[s[r_index]] += 1
            if len(table) > 2:
                while len(table) > 2:
                    table[s[l_index]] -= 1
                    if table[s[l_index]] == 0:
                        table.pop(s[l_index])
                    l_index += 1
            max_length = max(r_index - l_index + 1, max_length)
            r_index += 1
        return max_length


data = Solution()
s = "ccaabbb"
print(data.lengthOfLongestSubstringTwoDistinct(s))
